package cn.jwt.serviceImpl;

import cn.jwt.entity.SysUser;
import cn.jwt.service.SysMenuService;
import cn.jwt.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    //权限集合
    List<String> authorityList;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(SysUser::getUserName,username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        System.out.println("登录用户信息 = " + sysUser);
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或者密码错误！");
        }
        //TODO 查询对应的权限信息
        authorityList=sysMenuService.selectPermsByUserId(sysUser.getId());
        //把数据封装成UserDetails
        return new LoginSysUser(sysUser,authorityList);
    }
}
